package com.joymart.admin.rest;

import com.joymart.common.model.Range;
import com.joymart.common.utils.ExcelExporter;
import com.joymart.common.utils.SecurityUtils;
import com.joymart.order.service.OrderQueryService;
import com.joymart.user.model.CachedUser;
import com.joymart.user.model.User;
import com.joymart.user.service.UserCacheManager;
import com.joymart.user.service.UserService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

import static java.util.function.Predicate.not;


@RestController
@RequestMapping("/admin")
public class MemberReportAdminController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserCacheManager userCacheManager;


    @GetMapping("/members/export")
    public ResponseEntity<byte[]> export(){
        SecurityUtils.requiresRestAuthority("OperatingDataView");
        List<User> users = userService
                .findAll().stream().filter(not(User::isPartyA))
                .collect(Collectors.toList());
        return this.downloadExcel(users);
    }

    @SneakyThrows
    private ResponseEntity<byte[]> downloadExcel(List<User> users) {
        DateTimeFormatter parserFormat = DateTimeFormatter.ISO_DATE_TIME;
        DateTimeFormatter renderFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        ExcelExporter<User> memberExcelExporter = new ExcelExporter<>() {
            @Override
            protected String getSheetName() {
                return "会员列表";
            }

            @Override
            protected List<String> getHeaders() {
                return List.of("ID","姓名","性别","身份","身份最后变动时间","注册时间","城市","备注");
            }

        };

        Function<User, List<Object>> rowMapper  = user-> {
            CachedUser cachedUser = userCacheManager.get(user.getId());
            return Arrays.asList(
                    user.getId(), user.getNickname(),
                    "",
                    cachedUser.getHighestRole().getText(),
                    Optional.ofNullable(user.getMeta().optString("highestRoleLastModifiedAt"))
                            .filter(StringUtils::hasText)
                            .map(parserFormat::parse)
                            .map(renderFormat::format)
                    .orElse(""),
                    user.getCreatedAt(),
                    user.getMeta().opt("city"),
                    ""
            );
        };

        byte[] content = memberExcelExporter.exportToExcel(users, rowMapper);
        String fileName = "members-report.xlsx";

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+fileName);
        headers.add(HttpHeaders.CONTENT_TYPE, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");

        return new ResponseEntity<>(content, headers, HttpStatus.OK);
    }
}
